package com.by.controller;

import com.by.bean.ResultBean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class UploadController extends BaseController{
    private final String BASEDIR = "/attchment";//所有上传文件的根目录
    //单个上传
    @PostMapping("/upload")
    public ResultBean Upload(MultipartFile file , HttpServletRequest request){
        String url=toupload(file, request,null);
        return success("上传成功",url);
    }
    //批量上传
    @PostMapping("/uploads")
    public List uploads(List<MultipartFile> files, HttpServletRequest request){

        List<String> list=new ArrayList<>();
        //批量上传
        files.forEach(file -> {
            if (!file.isEmpty()) {
                String tmp = toupload(file, request,null);
                list.add(tmp);
            }
        });
        return list;
    }

    /**
     * 单个文件上传
     * @param file
     * @param request
     * @param type 默认为img
     * @return
     */
    String toupload(MultipartFile file,HttpServletRequest request,String type){
        //获取文件上传的根目录
        FilePath filePath=initDir(request,type);
        String newfile=newfilename(file);
        try {
            file.transferTo(new File(filePath.getRoot()+"\\"+newfile));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return filePath.getDir()+ newfile;
    }

    /**
     * 初始文件目录
     * @param request
     * @param type
     * @return
     */
    FilePath initDir(HttpServletRequest request,String type){
        if(type==null||"".equals(type)){
            type="images";
        }
        String relPath=BASEDIR+"/"+type+"/"+getSystemTime()+"/";
        //获取服务器上传根目录
        String root=request.getServletContext().getRealPath("/")+"/"+relPath;
        File dir=new File(root);
        if(!dir.exists()){
            dir.mkdirs();//创建目录
        }
        return new FilePath(dir.getAbsolutePath(),relPath);
    }
    class FilePath{
        String root;
        String dir;

        public FilePath(String root, String dir) {
            this.root = root;
            this.dir = dir;
        }

        public String getRoot() {
            return root;
        }

        public void setRoot(String root) {
            this.root = root;
        }

        public String getDir() {
            return dir;
        }

        public void setDir(String dir) {
            this.dir = dir;
        }
    }
    //获取新的文件名
    String newfilename(MultipartFile file){
        //获取上传文件的名称
        String name=file.getOriginalFilename();
        //获取文件的后缀
        String ext=name.substring(name.lastIndexOf("."));
        //新的文件名
        String newfile= UUID.randomUUID() +ext;
        return newfile;
    }
    //获取当前时间（年/月/日）
   String getSystemTime(){
       LocalDateTime dateTime=LocalDateTime.now();
       return  dateTime.format(DateTimeFormatter.ofPattern("yMMdd"));
   }
}
